<?php
namespace App\V3\V3_1\Services;

use App\V3\V3_1\Models\SellDriverModel;
use App\V3\V3_1\Models\StorageManageModel;
use App\V3\V3_1\Models\SellGoodsDetailModel;
use App\V3\V3_1\Models\SellModel;
use App\V3\V3_1\Models\SellPackageContentModel;
use Illuminate\Support\Facades\DB;
use App\V3\V3_1\Models\AdminModel;
use App\V3\V3_1\Models\AdminAddendumModel;

class SellsService
{
    static public function exportData($userId, $data)
    {
        $adminInfo = AdminModel::where('id', $userId)->first();

        if($adminInfo['parent_id'] == 0 || $adminInfo['parent_id'] == $userId) {

            $condition['a.main_id'] = ['EQ' => $userId];

        }else {

            $adminAddendumInfo = AdminAddendumModel::select('is_share_sell')->where('main_id',$adminInfo['parent_id'])->first();

            if($adminAddendumInfo['is_share_sell'] == 1) {

                $condition['a.main_id'] = ['EQ' => $adminInfo['parent_id']];
            }else {

                $condition['a.user_id'] = ['EQ' => $userId];
            }
        }

        //搜索类型
        if(!empty($data['keyword'])) {//关键词搜索组是否启用
            switch($data['search_type']) {

                //1->商品名称;2->商品编号
                case 1:
                case 2:
                    $result = self::searchGoodsInfo($condition, $data);
                    break;
                    //搜索内部单号
                case 3:
                    $result = self::searchInnerOrderNo($condition, $data);
                    break;
                    //搜索外部单号
                case 4:
                    $result = self::searchOutOrderNo($condition, $data);
                    break;
                    //搜索快递单号
                case 5:
                    $result = self::searchExpressNo($condition, $data);
                    break;
                    //搜索客户姓名
                case 6:
                    $result = self::searchCustomerName($condition, $data);
                    break;
                    //搜索司机姓名
                case 7:
                    $result = self::searchDriverName($condition, $data);
                    break;
                    //搜索发货人姓名
                case 8:
                    $result = self::searchSenderName($condition, $data);
                    break;
            }
        }
        else {

            return self::searchWithoutKeyword($condition, $data);
        }

        return $result;
    }

    static private function searchSenderName($userId, $data)
    {
        $condition[] = ['deliver_person', 'like', '%'.$data['keyword'].'%'];
        $sellInfo = SellModel::getSellIdInfo($userId, $data, $condition);

        $sellId = [];
        foreach($sellInfo as $value) {
            $sellId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $sellId);
    }

    //搜索司机姓名
    static private function searchDriverName($userId, $data)
    {
        //获取用户对应的销售单id
        $sellInfo = SellModel::getSellInfo($userId);

        $sellIdArr = [];
        foreach($sellInfo as $value) {
            $sellIdArr[] = $value['id'];
        }

        $condition['name'] = ['EQ' => $data['keyword']];

        $sellDriverInfo = SellDriverModel::getSellDriverInfo($sellIdArr, $condition);

        $sellId = [];
        foreach($sellDriverInfo as $value) {
            $sellId[] = $value['sell_id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $sellId);
    }

    //内部单号搜索
    static private function searchCustomerName($userId, $data)
    {
        $condition[] = ['customer_name', 'like', '%'.$data['keyword'].'%'];
        $sellInfo = SellModel::getSellIdInfo($userId, $data, $condition);

        $sellId = [];
        foreach($sellInfo as $value) {
            $sellId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $sellId);
    }

    //商品信息搜索
    static private function searchGoodsInfo($userId, $data)
    {
        $sellInfo = SellModel::getSellInfo($userId);

        $sellIdArr = [];
        foreach($sellInfo as $value) {
            $sellIdArr[] = $value['id'];
        }

        $condition = [];
        $condition1 = [];
        if($data['search_type'] == 1) {
            $condition[] = ['b.materiel_name', 'like', '%'.$data['keyword'].'%'];
            $condition1[] = ['materiel_name', 'like', '%'.$data['keyword'].'%'];
        }
        else if($data['search_type'] == 2) {
            $condition[] = ['b.materiel_no', 'like', '%'.$data['keyword'].'%'];
            $condition1[] = ['materiel_no', 'like', '%'.$data['keyword'].'%'];
        }

        $sellDetailSellIdInfo = SellGoodsDetailModel::getGoodsDetailInfo($sellIdArr, $condition);

        //查找销售单套餐内指定商品的的信息-商品id
        $sellPackageContentInfo = SellPackageContentModel::getSellPackageContent($userId, $condition1);

        $sellIdArr = [];
        foreach($sellDetailSellIdInfo as $value) {
            $sellIdArr[] = $value['sell_id'];
        }

        //获取商品信息和套餐内商品信息的销售单id集合
        foreach($sellPackageContentInfo as $val) {
            if(!in_array($val['sell_id'], $sellIdArr)) {
                array_push($sellIdArr, $val['sell_id']);
            }
        }

        return self::commonSearchWithKeyword($userId, $data, $sellIdArr);
    }

    //内部单号搜索
    static private function searchInnerOrderNo($userId, $data)
    {
        $condition[] = ['order_no', 'like', '%'.$data['keyword'].'%'];
        $sellInfo = SellModel::getSellIdInfo($userId, $data, $condition);

        $sellId = [];
        foreach($sellInfo as $value) {
            $sellId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $sellId);
    }

    //外部单号搜索
    static private function searchOutOrderNo($userId, $data)
    {
        $condition[] = ['out_order_no', 'like', '%'.$data['keyword'].'%'];
        $sellInfo = SellModel::getSellIdInfo($userId, $data, $condition);

        $sellId = [];
        foreach($sellInfo as $value) {
            $sellId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $sellId);
    }

    //快递单号检索
    static private function searchExpressNo($userId, $data)
    {
        $condition[] = ['logistics_order_no', 'like', '%'.$data['keyword'].'%'];
        $sellInfo = SellModel::getSellIdInfo($userId, $data, $condition);

        $sellId = [];
        foreach($sellInfo as $value) {
            $sellId[] = $value['id'];
        }

        return self::commonSearchWithKeyword($userId, $data, $sellId);
    }

    //使用关键词检索
    static private function commonSearchWithKeyword($userId, $data, $sellIdArr)
    {/* DB::enableQueryLog(); */
        $query = SellModel::select(
            'a.*',
            'b.username',
            'b.nickname'
            )
            ->from('sell as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with('materielInfo', function($query) {
                $query->select(
                    'sell_goods_detail.id as sell_goods_id',
                    'a.materiel_name as name',
                    'a.type_name',
                    'a.materiel_no',
                    'a.materiel_img as image',
                    'price',
                    'sell_goods_detail.num',
                    'b.storage_name as warehouse',
                    'b.id as warehouse_id',
                    'piece',
                    'sell_goods_detail.materiel_type_id',
                    'sell_goods_detail.sell_id',
                    'sell_goods_detail.shelf_id',
                    'sell_goods_detail.location_id',
                    'sell_goods_detail.id as sid',
                    'cost_price',
                    'a.is_use_serial',
                    'cost_price',
                    'se.shelf_name',
                    'lo.location_name',
                    'a.materiel_class_id',
                    )->leftJoin('materiel_type as a', 'a.id', '=', 'sell_goods_detail.materiel_type_id')
                    ->leftJoin('storage as b', 'b.id', '=', 'sell_goods_detail.warehouse_id')
                    ->leftJoin('storage_shelf as se','sell_goods_detail.shelf_id','=','se.id')
                    ->leftJoin('storage_shelf_location as lo','sell_goods_detail.location_id','=','lo.id');
            })
            ->with('packageInfo', function($query) {
                $query->select(
                    'sell_package_detail.id',
                    'package_id',
                    'package_name',
                    'price',
                    'total_cost',
                    'sell_id',
                    'num',
                    'out_num'
                    )
                    ->leftJoin('package as p', 'p.id', '=', 'sell_package_detail.package_id')
                    ->with('packageContent', function($query) {
                        $query->select(
                            'sell_package_content.id',
                            'sell_package_content.num',
                            'sell_package_content.materiel_type_id',
                            'sell_package_content.shelf_id',
                            'sell_package_content.location_id',
                            'package_detail_id',
                            'mt.materiel_name',
                            'mt.type_name',
                            'mt.materiel_no',
                            'mt.materiel_img',
                           'mt.cost',
                            'mcs.class_name as s_class_name',
                            'mcs.class_no as s_class_no',
                            'mcf.class_name as f_class_name',
                            'mcf.class_no as f_class_no',
                            's.storage_name',
                            'sm.in_storage_num',
                            'mt.is_use_serial',
                            'sell_package_content.storage_manage_id',
                            'sell_package_content.shelf_id',
                            'sell_package_content.location_id',
                            'se.shelf_name',
                            'lo.location_name'
                            )
                            ->leftJoin('materiel_type as mt', 'mt.id', '=', 'sell_package_content.materiel_type_id')
                            ->leftJoin('materiel_class as mcs', 'mcs.id', '=', 'sell_package_content.materiel_class_id')
                            ->leftJoin('materiel_class as mcf', 'mcf.id', '=', 'mcs.parent_id')
                            ->leftJoin('storage_manage as sm', 'sm.id', '=', 'sell_package_content.storage_manage_id')
                            ->leftJoin('storage as s', 's.id', '=', 'sell_package_content.storage_id')
                            ->leftJoin('storage_shelf as se','sell_package_content.shelf_id','=','se.id')
                            ->leftJoin('storage_shelf_location as lo','sell_package_content.location_id','=','lo.id');

                    });
            })
            ->with('driverInfo', function($query) {
                $query->select(
                    'id',
                    'plate_number',
                    'name',
                    'phone',
                    'logistics_company',
                    'remark',
                    'plate_image',
                    'id_card_image',
                    'driving_licence',
                    'sell_id'
                    );
            })
            ->where([
                'repeal_status' => $data['repeal_status']
            ])
            ->where($userId);

            if(!empty($data['start_time'])) {
                $startTimeArr = explode(' ', $data['start_time']);
                $startTime = strtotime($startTimeArr[0].' 00:00:00');
            }

            if(!empty($data['end_time'])) {
                $endTimeArr = explode(' ', $data['end_time']);
                $endTime = strtotime($endTimeArr[0].' 23:59:59');
            }

            if(!empty($startTime) && !empty($endTime)) {
                $query->whereBetween('sell_time', [$startTime, $endTime]);
            }
            else if(!empty($startTime) && empty($endTime)) {
                $query->where('sell_time', '>=', $startTime);
            }
            else if(empty($startTime) && !empty($endTime)) {
                $query->where('sell_time', '<=', $endTime);
            }

            //销售单状态
            switch($data['status']) {
                //新订单
                case 1:
                    $query->where('out_status', 0);
                    $query->where('pay_status', 0);
                    break;
                    //已收款
                case 2:
                    $query->whereIn('pay_status', [1,2]);
                    $query->where('out_status', 0);
                    break;
                    //已完结
                case 3:
                    $query->where('out_status', 2);
                    $query->where('pay_status', 2);
                    break;
                    //已出库
                case 4:
                    $query->where('pay_status', 0);
                    $query->whereIn('out_status', [1,2]);
                    break;
                    //预出库(未付款)
                case 5:
                    $query->where('prepare_out_status', 1);
                    $query->where('pay_status', 0);
                    break;
                    //预出库(未付款)
                case 6:
                    $query->where('prepare_out_status', 1);
                    $query->whereIn('pay_status', [1,2]);
                    break;
            }

            $query =  $query->whereIn('a.id', $sellIdArr)
            ->orderBy('a.id','desc');

            if(!empty($data['currentPage'])){

                $query =  $query->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();

            }else{
                $query =  $query->get()->toArray();
            }

            if(isset($query['data'])){
                foreach($query['data'] as &$value) {
                    foreach($value['materiel_info'] as $k => $val) {
                        $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                        ->where('storage_id', $val['warehouse_id'])->first();

                        $value['materiel_info'][$k]['storage_manage_id'] = $storageManageInfo['id'];
                        $value['materiel_info'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
                    }
                }
            }else{
                foreach($query as &$value) {
                    foreach($value['materiel_info'] as $k => $val) {
                        $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                        ->where('storage_id', $val['warehouse_id'])->first();

                        $value['materiel_info'][$k]['storage_manage_id'] = $storageManageInfo['id'];
                        $value['materiel_info'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
                    }
                }
            }

            return $query;
    }

    static private function searchWithoutKeyword($userId, $data)
    {
        $query = SellModel::select(
            'a.*',
            'b.username',
            'b.nickname'
            )
            ->from('sell as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with('materielInfo', function($query) {
                $query->select(
                    'a.materiel_name as name',
                    'a.type_name',
                    'a.materiel_no',
                    'a.materiel_img as image',
                    'price',
                    'sell_goods_detail.num',
                    'b.storage_name as warehouse',
                    'b.id as warehouse_id',
                    'piece',
                    'sell_id',
                    'cost_price',
                    'sell_goods_detail.id as sid',
                    'sell_goods_detail.materiel_type_id',
                    'sell_goods_detail.shelf_id',
                    'sell_goods_detail.location_id',
                    'se.shelf_name',
                    'lo.location_name',
                     'a.is_use_serial',
                    'a.materiel_class_id',
                   /*  'a.is_product_materiel' */
                    )->leftJoin('materiel_type as a', 'a.id', '=', 'sell_goods_detail.materiel_type_id')
                    ->leftJoin('storage as b', 'b.id', '=', 'sell_goods_detail.warehouse_id')
                    ->leftJoin('storage_shelf as se','sell_goods_detail.shelf_id','=','se.id')
                    ->leftJoin('storage_shelf_location as lo','sell_goods_detail.location_id','=','lo.id');
            })
            ->with('packageInfo', function($query) {
                $query->select(
                    'sell_package_detail.id',
                    'package_id',
                    'package_name',
                    'price',
                    'total_cost',
                    'sell_id',
                    'num',
                    'out_num'
                    )
                    ->leftJoin('package as p', 'p.id', '=', 'sell_package_detail.package_id')
                    ->with('packageContent', function($query) {
                        $query->select(
                            'sell_package_content.id',
                            'sell_package_content.num',
                            'sell_package_content.materiel_type_id',
                            'package_detail_id',
                            'mt.materiel_name',
                            'mt.type_name',
                            'mt.materiel_no',
                            'mt.materiel_img',
                            'mcs.class_name as s_class_name',
                            'mcs.class_no as s_class_no',
                            'mcf.class_name as f_class_name',
                            'mcf.class_no as f_class_no',
                            's.storage_name',
                            'sm.in_storage_num',
                            'sell_package_content.shelf_id',
                            'sell_package_content.location_id',
                            'se.shelf_name',
                            'lo.location_name',
                            'mt.is_use_serial',
                            'sell_package_content.storage_manage_id'
                            )
                            ->leftJoin('materiel_type as mt', 'mt.id', '=', 'sell_package_content.materiel_type_id')
                            ->leftJoin('materiel_class as mcs', 'mcs.id', '=', 'sell_package_content.materiel_class_id')
                            ->leftJoin('materiel_class as mcf', 'mcf.id', '=', 'mcs.parent_id')
                            ->leftJoin('storage_manage as sm', 'sm.id', '=', 'sell_package_content.storage_manage_id')
                            ->leftJoin('storage as s', 's.id', '=', 'sell_package_content.storage_id')
                            ->leftJoin('storage_shelf as se','sell_package_content.shelf_id','=','se.id')
                            ->leftJoin('storage_shelf_location as lo','sell_package_content.location_id','=','lo.id');
                    });
            })
            ->with('driverInfo', function($query) {
                $query->select(
                    'id',
                    'plate_number',
                    'name',
                    'phone',
                    'logistics_company',
                    'remark',
                    'plate_image',
                    'id_card_image',
                    'driving_licence',
                    'sell_id'
                    );
            })
            ->where([
                'repeal_status' => $data['repeal_status']
            ])
            ->where('a.delete_flag',0)
            ->where($userId);

            if(!empty($data['start_time'])) {
                $startTimeArr = explode(' ', $data['start_time']);
                $startTime = strtotime($startTimeArr[0].' 00:00:00');
            }

            if(!empty($data['end_time'])) {
                $endTimeArr = explode(' ', $data['end_time']);
                $endTime = strtotime($endTimeArr[0].' 23:59:59');
            }

            if(!empty($startTime) && !empty($endTime)) {
                $query->whereBetween('sell_time', [$startTime, $endTime]);
            }
            else if(!empty($startTime) && empty($endTime)) {
                $query->where('sell_time', '>=', $startTime);
            }
            else if(empty($startTime) && !empty($endTime)) {
                $query->where('sell_time', '<=', $endTime);
            }

            //销售单状态
            switch($data['status']) {
                //新订单
                case 1:
                    $query->where('out_status', 0);
                    $query->where('pay_status', 0);
                    break;
                    //已收款
                case 2:
                    $query->whereIn('pay_status', [1,2]);
                    $query->where('out_status', 0);
                    break;
                    //已完结
                case 3:
                    $query->where('out_status', 2);
                    $query->where('pay_status', 2);
                    break;
                    //已出库
                case 4:
                    $query->where('pay_status', 0);
                    $query->whereIn('out_status', [1,2]);
                    break;
                    //预出库(未付款)
                case 5:
                    $query->where('prepare_out_status', 1);
                    $query->where('pay_status', 0);
                    break;
                    //预出库(已付款)
                case 6:
                    $query->where('prepare_out_status', 1);
                    $query->whereIn('pay_status', [1,2]);
                    break;
            }

            if(!empty($data['currentPage'])){

                $query =  $query->orderBy('a.id','desc')->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();

            }else{

                $query = $query->orderBy('a.id','desc')->get()->toArray();
            }

            if(!empty($query['data'])){

                foreach($query['data'] as &$value) {
                    if(!empty($value['materiel_info'])){
                        foreach($value['materiel_info'] as $k => $val) {
                            //                $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                            //                    ->where('storage_id', $val['warehouse_id'])->first();

                            $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                            ->where('storage_id', $val['warehouse_id'])->where(['shelf_id'=>$val['shelf_id'],'location_id'=>$val['location_id']])->first();

                            $value['materiel_info'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
                        }
                    }
                }
            }

            return $query;
    }
}
